const express = require('express');
const router = express.Router();
const db = require('../models/database');
console.log('数据库连接状态:', db.open ? '已连接' : '未连接');

// 获取所有商品
router.get('/', (req, res) => {
    db.all('SELECT * FROM products', [], (err, rows) => {
        if (err) {
            return res.status(500).json({ error: err.message });
        }
        res.json(rows);
    });
});

// 获取单个商品
router.get('/:id', (req, res) => {
    const { id } = req.params;
    db.get('SELECT * FROM products WHERE id = ?', [id], (err, row) => {
        if (err) {
            return res.status(500).json({ error: err.message });
        }
        if (!row) {
            return res.status(404).json({ error: 'Product not found' });
        }
        res.json(row);
    });
});

// 添加商品
router.post('/', (req, res) => {
    const { name, description, category, price } = req.body;
    if (!name) {
        return res.status(400).json({ error: 'Product name is required' });
    }
    
    db.run(
        'INSERT INTO products (name, description, category, price) VALUES (?, ?, ?, ?)',
        [name, description, category, price],
        function(err) {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            res.json({ id: this.lastID, name, description, category, price });
        }
    );
});

// 更新商品
router.put('/:id', (req, res) => {
    const { id } = req.params;
    const { name, description, category, price } = req.body;
    
    db.run(
        'UPDATE products SET name = ?, description = ?, category = ?, price = ? WHERE id = ?',
        [name, description, category, price, id],
        function(err) {
            if (err) {
                return res.status(500).json({ error: err.message });
            }
            if (this.changes === 0) {
                return res.status(404).json({ error: 'Product not found' });
            }
            res.json({ id, name, description, category, price });
        }
    );
});

// 删除商品
router.delete('/:id', (req, res) => {
    const { id } = req.params;
    
    db.run('DELETE FROM products WHERE id = ?', [id], function(err) {
        if (err) {
            return res.status(500).json({ error: err.message });
        }
        if (this.changes === 0) {
            return res.status(404).json({ error: 'Product not found' });
        }
        res.json({ message: 'Product deleted successfully' });
    });
});

module.exports = router;